package config

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"github.com/gogf/gf/v2/errors/gerror"
)

// GroupTreeList 获取配置组树形列表
func (c *sConfig) GroupTreeList(ctx context.Context, in model.ConfigGroupTreeListInput) (treeList []model.ConfigGroupTreeItem, err error) {
	var (
		rows = []model.ConfigGroupCategoryItem{}
	)
	// 获取分组列表
	err = dao.ConfigGroup.Ctx(ctx).
		OmitEmpty().
		Where(in).
		Scan(&rows)
	if err != nil {
		return nil, gerror.Wrapf(err, `获取分组列表错误%s`, err.Error())
	}
	// 递归树形列表
	return c.groupTreeListHandler(rows, 0), nil
}

// GroupDetail 获取配置详情
func (c *sConfig) GroupDetail(ctx context.Context, id uint) (detail *model.ConfigGroupCategoryItem, err error) {
	detail = &model.ConfigGroupCategoryItem{}
	// 获取数据
	err = c.ProcessGroupDetailById(ctx, id, &detail)
	return
}

// groupTreeListHandler 递归配置组树形结构处理
func (c *sConfig) groupTreeListHandler(list []model.ConfigGroupCategoryItem, pid uint) (treeList []model.ConfigGroupTreeItem) {
	if len(list) == 0 {
		return []model.ConfigGroupTreeItem{}
	}
	// 初始化
	treeList = make([]model.ConfigGroupTreeItem, 0)
	childList := make([]model.ConfigGroupCategoryItem, 0) // 初始化子级列表

	// 迭代根节点数据并排除子节点
	for _, item := range list {
		if item.Pid != pid {
			// 记录子节点并排除根节点，避免每次都迭代
			childList = append(childList, item)
			continue
		}
		// 根节点树形数据并初始化子节点
		treeList = append(treeList, model.ConfigGroupTreeItem{
			ConfigGroupCategoryItem: item,
			Children:                []model.ConfigGroupTreeItem{},
		})
	}

	// 迭代子节点
	for key, tree := range treeList {
		treeList[key].Children = c.groupTreeListHandler(childList, tree.Id)
	}
	return treeList
}
